<?php


namespace app\command;


use app\service\statistics\StatisticProvider;
use app\service\statistics\StatisticWorker;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Workerman\Worker;

class StatisticsCommand extends \Symfony\Component\Console\Command\Command
{

    protected static $defaultName = 'config:statistics';
    protected static $defaultDescription = 'Statistics服务配置';

    protected function configure()
    {
        $this
            // 命令的名称 ("php console_command" 后面的部分)
            //->setName('model:create')
            // 运行 "php console_command list" 时的简短描述
            ->setDescription('Create new model')
            // 运行命令时使用 "--help" 选项时的完整命令描述
            ->setHelp('This command allow you to create models...')
            // 配置一个参数
            ->addArgument('name', InputArgument::REQUIRED, 'what\'s model you want to create ?');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        global $argv;
//        $argv[2] = 'start';
        $argv[3] = '-d';

        $output->writeln('Statistics服务配置信息如下：');
        $statistic_worker = new StatisticWorker("Statistic://0.0.0.0:55656");
        $statistic_worker->transport = 'udp';
        $statistic_worker->name = 'StatisticWorker';
        $statistic_provider = new StatisticProvider("Text://0.0.0.0:55858");
        $statistic_provider->name = 'StatisticProvider';
        $statistic_provider->onMessage = function ($connection, $data)
        {
            $data = json_decode($data, true);
            if(empty($data))
            {
                return false;
            }
            // 无法解析的包
            if(empty($data['cmd']) || $data['cmd'] != 'REPORT_IP' )
            {
                return false;
            }
            // response
            return $connection->send(json_encode(array('result'=>'ok')));
        };
        Worker::runAll();
        return self::SUCCESS;
    }


}
